import { getFileReader } from '/lib/DirectoryPicker';
import { openDirectory } from './FileSystemAccess';
import { ref, reactive } from 'vue';
export default function (textarea) {
  // 树状图props
  const defaultProps = {
    children: 'children',
    label: 'name',
    isLeaf: (data) => data.kind !== 'directory',
    class: (data) => data.kind,
  };

  // tree操作对象
  const tree = ref(null);

  // 树状图内容
  const data = ref([]);

  // 当前选择的
  const select = reactive({
    data: null,
    node: null,
    type: null,
  });

  // 点击文件时
  const handleNodeClick = async (data, node) => {
    select.data = data;
    select.node = node;
    select.type = data.kind;
    if (data.kind !== 'directory') {
      const file = await data.getFile();
      select.type = file.type;
      if (file.type == 'text/plain') {
        textarea.type = 'text';
        const f = await getFileReader(file);

        textarea.value = f;
      } else if (/^image\//.test(file.type)) {
        textarea.type = 'image';
        textarea.value = URL.createObjectURL(file);
      } else {
        textarea.value = null;
        textarea.type = null;
      }
    } else {
      textarea.type = null;
      textarea.value = null;
    }
  };

  // 打开子分支
  const loadNode = async (node, resolve) => {
    return resolve(await openDirectory(node.data));
  };

  return {
    defaultProps,
    data,
    tree,
    select,
    handleNodeClick,
    loadNode,
  };
}
